﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using PepsiCo.Common;
using T2V.SharePoint.Common.Extensions;
using Microsoft.SharePoint.Administration;

namespace PepsiCo.RBS.EventReceivers.WaitEventEventReceiver
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class WaitEventEventReceiver : SPItemEventReceiver
    {
       /// <summary>
       /// An item is being added.
       /// </summary>
       public override void ItemAdding(SPItemEventProperties properties)
       {
           base.ItemAdding(properties);
           SetLocation(properties);
           EnsureUserWaitEvent(properties);
       }

       /// <summary>
       /// An item is being updated.
       /// </summary>
       public override void ItemUpdating(SPItemEventProperties properties)
       {
           base.ItemUpdating(properties);
           if (!PreventAccessOnRecurringItem(properties))
           {
               SetLocation(properties);
               EnsureUserWaitEvent(properties);
           }
       }

       /// <summary>
       /// An item is being deleted.
       /// </summary>
       public override void ItemDeleting(SPItemEventProperties properties)
       {
           base.ItemDeleting(properties);
           if (!PreventAccessOnRecurringItem(properties))
           { 
           
           }
       }

       public void SetLocation(SPItemEventProperties properties)
       {
           try
           {
               string location = string.Empty;

               SPWeb spWeb = properties.Web;

               if (properties.AfterProperties[PepsiCoConstants.WaitEvent.MEETING_ROOM_COLUMN] != null && !string.IsNullOrEmpty(properties.AfterProperties[PepsiCoConstants.WaitEvent.MEETING_ROOM_COLUMN].ToString()))
               {
                   SPList spListMeetingRoom = spWeb.GetList(spWeb.ServerRelativeUrl.TrimEnd('/') + PepsiCoConstants.MeetingRoom.LIST_URL);
                   SPListItem spItemMeetingRoom = spListMeetingRoom.GetItemById(Convert.ToInt32(properties.AfterProperties[PepsiCoConstants.WaitEvent.MEETING_ROOM_COLUMN].ToString()));

                   location = spItemMeetingRoom.Title;

                   if (spItemMeetingRoom[PepsiCoColumnId.MeetingRoom.RoomLocation] != null && !string.IsNullOrEmpty(spItemMeetingRoom[PepsiCoColumnId.MeetingRoom.RoomLocation].ToString()))
                   {
                       location += " - " + spItemMeetingRoom[PepsiCoColumnId.MeetingRoom.RoomLocation].ToString();
                   }
               }

               properties.AfterProperties[PepsiCoConstants.WaitEvent.LOCATION_COLUMN] = location;
           }
           catch (Exception ex)
           {
               SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("WaitEventEventReceiver SetLocation", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
           }
       }

       public void EnsureUserWaitEvent(SPItemEventProperties properties)
       {
           try
           {
               SPWeb spWeb = properties.Web;

               if (properties.AfterProperties[PepsiCoConstants.WaitEvent.USER_COLUMN] != null && !string.IsNullOrEmpty(properties.AfterProperties[PepsiCoConstants.WaitEvent.USER_COLUMN].ToString()))
               {
                   SPUser user = spWeb.EnsureUserByLookupValue(properties.AfterProperties[PepsiCoConstants.WaitEvent.USER_COLUMN].ToString());

                   if (properties.AfterProperties[PepsiCoConstants.WaitEvent.EMAIL_COLUMN] != null && properties.AfterProperties[PepsiCoConstants.WaitEvent.EMAIL_COLUMN].ToString() != user.Email)
                   {
                       properties.AfterProperties[PepsiCoConstants.WaitEvent.EMAIL_COLUMN] = user.Email;
                   }
               }
           }
           catch (Exception ex)
           {
               SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("WaitEventEventReceiver EnsureUserWaitEvent", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
           }
       }

       public bool PreventAccessOnRecurringItem(SPItemEventProperties properties)
       {
           bool result = false;

           try
           {
               SPWeb spWeb = properties.Web;

               var listWaitEvent = properties.List;
               var itemWaitEvent = properties.ListItem;

               if (listWaitEvent.WriteSecurity == 2 && !spWeb.DoesUserHavePermissions(SPBasePermissions.FullMask))
               {
                   var authorUser = spWeb.EnsureSPFieldUserValueByLookupValue(itemWaitEvent[SPBuiltInFieldId.Author].ToString());

                   if (authorUser.User.LoginName != properties.UserLoginName)
                   {
                       result = true;

                       properties.ErrorMessage = "Access Denied";
                       properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
                       properties.RedirectUrl = "_layouts/AccessDenied.aspx";
                       properties.Cancel = true;
                   }
               }
           }
           catch (Exception ex)
           {
               SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("WaitEventEventReceiver PreventAccessOnRecurringItem", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
           }

           return result;
       }
    }
}
